import base64
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad

class AESCipher:
    def __init__(self, key='BmqGgcpSyvBli36N', iv='u112ZfIPYfFxK49C'):
        """
        初始化AES加密解密类
        :param key: 16字节的密钥
        :param iv: 16字节的初始化向量
        """
        self.key = key.encode('utf-8')
        self.iv = iv.encode('utf-8')
    
    def encrypt(self, data):
        """
        AES-CBC加密
        :param data: 待加密的字符串
        :return: base64编码的密文
        """
        if isinstance(data, str):
            data = data.encode('utf-8')
        
        cipher = AES.new(self.key, AES.MODE_CBC, self.iv)
        padded_data = pad(data, AES.block_size)
        encrypted = cipher.encrypt(padded_data)
        return base64.b64encode(encrypted).decode('utf-8')
    
    def decrypt(self, encrypted_data):
        """
        AES-CBC解密
        :param encrypted_data: base64编码的密文
        :return: 解密后的明文
        """
        if isinstance(encrypted_data, str):
            encrypted_data = encrypted_data.encode('utf-8')
        
        encrypted_data = base64.b64decode(encrypted_data)
        cipher = AES.new(self.key, AES.MODE_CBC, self.iv)
        decrypted = unpad(cipher.decrypt(encrypted_data), AES.block_size)
        return decrypted.decode('utf-8')